package org.darkforest.merchant.controller;

import org.darkforest.common.captcha.GeetestLib;
import org.darkforest.common.services.*;
import org.darkforest.dao.mapper.OrderStatisticsMapper;
import org.darkforest.dao.mapper.SellerGroupMapper;
import org.darkforest.enums.SettingNameEnum;
import org.darkforest.model.*;
import org.darkforest.ucenter.auth.AuthPassport;
import org.darkforest.ucenter.service.SellerService;
import org.darkforest.vo.StoreSellerVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by chenyu on 15/1/18.
 */
@Controller
public class MainController {
    static final Logger logger = LoggerFactory.getLogger(MainController.class);

    @Autowired
    private SellerService sellerService;
    @Autowired
    SellerGroupMapper groupMapper;

    @Autowired
    private SettingService settingService;

//    @Autowired
//    private StatOrderGoodsService statOrderGoodsService;
    @Autowired
    private OrderStatisticsMapper orderStatisticsMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private HelpTypeService helpTypeService;

    @Autowired
    private RefundReturnService refundReturnService;

    private static String captcha_id = "1e8ebbd159c27968985d930198fc6006";
    private static String private_key = "dd84b657f4353c2755562bf00297290e";

    /**
     * 转到登录页面
     * @param request
     * @return
     */
    @RequestMapping(value="/")
    public String index(HttpServletRequest request){
        GeetestLib geetestSdk = new GeetestLib();
        geetestSdk.setCaptchaId(captcha_id);
//        geetestSdk.setProductType("");
        geetestSdk.getChallengeId();
        String gee_str = geetestSdk.getGtFrontSource();
        request.setAttribute("gee_str",gee_str);
        return "login";
    }

    @RequestMapping("/verfiyCaptcha")
    public String verfiyCaptcha(HttpServletRequest request){
        String gtResult = "false";
        GeetestLib geetest = new GeetestLib(private_key);
        if (geetest.resquestIsLegal(request)) {
            gtResult = geetest.enhencedValidateRequest(request);
            System.out.println(gtResult);
        } else {
            gtResult = "fail";

        }
        return gtResult;
    }

    /**
     * 登录
     * @return
     */
    @RequestMapping(value="/login",method = RequestMethod.POST)
    public String login(HttpServletRequest request,String seller_name,String password,String invalidStr){

        StoreSellerVo sellerVo = sellerService.sellerLogin(seller_name,  password);
        if(sellerVo==null){
            //登录失败
            request.setAttribute("msg","用户名密码错误");
            request.setAttribute("url","/");
            return "sysMessage";
        }else{
            if (sellerVo.getStoreState() == 0) {
                //登录失败
                request.setAttribute("msg","店铺处于关闭状态，请联系运维人员开启店铺");
                request.setAttribute("url","/");
                return "sysMessage";
            } else if (sellerVo.getStoreState() == 1) {
                //登录成功，将商户信息存储到session中
                request.getSession().setAttribute("sellerInfo",sellerVo);
                int groupId = sellerVo.getSellerGroupId();
                SellerGroupWithBLOBs group = groupMapper.selectByPrimaryKey(groupId);
                request.getSession().setAttribute("group",group);
            } else if (sellerVo.getStoreState() == 2) {
                //登录失败
                request.setAttribute("msg","店铺处于待审核状态，请联系运维人员确认店铺审核状况");
                request.setAttribute("url","/");
                return "sysMessage";
            }
        }
        return "redirect:/main";
    }

    /**
     * 首页
     * @param session
     * @return
     */
    @AuthPassport
    @RequestMapping(value="/main")
    public String main(HttpSession session){

        //session过期,重新跳转到登录页面
        if(session.getAttribute("sellerInfo")==null){
            String basePath = (String)session.getServletContext().getAttribute("basePath");
            return "redirect:/";
        }

        StoreSellerVo store = (StoreSellerVo)session.getAttribute("sellerInfo");
        Integer storeId =store.getStoreId();

        //查询统计：
        // 1]图片使用量：
        int picNum = sellerService.getPicNum(storeId);
        // 2]出售中商品数量
        int sellingGoods = sellerService.getGoodsNum(storeId,1, 1);
        // 3]仓库中商品数量
        int storeGoods1 = sellerService.getGoodsNum(storeId, 0, 1);
        int storeGoods2 = sellerService.getGoodsNum(storeId, 10, 1);
        int storeGoods = storeGoods1 + storeGoods2;
        // 4]待审核商品数量
        int verifyGoods = sellerService.getGoodsNum(storeId, 1, 10);

        //单品销量排行统计
        List<OrderStatistics> statOrderGoodsList = orderStatisticsMapper.findTopOrderAmount(storeId);
        int topIndex = 1;
        for (OrderStatistics orderStatistics:statOrderGoodsList) {
            orderStatistics.setSort(topIndex++);
        }
        //销售情况统计  按周期统计商家店铺的订单量和订单金额
        List<OrderStatistics> recentlyOrderAmount = orderStatisticsMapper.findRecentlyOrderAmount(storeId);

        //平台联系方式
        String siteEmail = settingService.getSettingInfo(SettingNameEnum.SITE_EMAIL);
        String sitePhone = settingService.getSettingInfo(SettingNameEnum.SITE_PHONE);
        String sitePhone1 = settingService.getSettingInfo(SettingNameEnum.SITE_PHONE1);

        //帮助指南
        List<HelpType> helpTypeList =helpTypeService.findProxyHelpClassByCondition(new HelpType());

        //交易提示 才处理订单
        Map<String,Object> map = orderService.findTransactionInfo(storeId);
        //退款状态统计 //flag 退款退货标识
        Map<String,Object> refunMoney = refundReturnService.refundMoneyAndGoodsStatistics(1, storeId);
        //退货状态统计 //flag 退款退货标识
        Map<String,Object> refunGoods = refundReturnService.refundMoneyAndGoodsStatistics(2, storeId);

        session.setAttribute("picNum",picNum);
        session.setAttribute("sellingGoods",sellingGoods);
        session.setAttribute("storeGoods",storeGoods);
        session.setAttribute("verifyGoods",verifyGoods);
        session.setAttribute("goodsNum",sellingGoods+storeGoods+verifyGoods);
        session.setAttribute("statisticsEntry",statOrderGoodsList);
        session.setAttribute("recentlyOrderAmount",recentlyOrderAmount);
        session.setAttribute("siteEmail",siteEmail);
        session.setAttribute("sitePhone",sitePhone);
        session.setAttribute("sitePhone1",sitePhone1);
        session.setAttribute("helpTypeList",helpTypeList);
        session.setAttribute("pcweb_site",settingService.getSettingInfo(SettingNameEnum.PCWEBSITE));
        session.setAttribute("orderState",map);
        session.setAttribute("refunMoney",refunMoney);
        session.setAttribute("refunGoods",refunGoods);

        return "main";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        //清除登录信息，跳转到登录页面
        session.removeAttribute("sellerInfo");
        session.removeAttribute("picNum");
        session.removeAttribute("sellingGoods");
        session.removeAttribute("storeGoods");
        session.removeAttribute("goodsNum");
        session.removeAttribute("group");
        return "redirect:/";
    }
}
